package com.ehsunbehravesh.mypasswords;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class VersionChecker implements Runnable { 
  private JFrame parent;

  public VersionChecker(JFrame parent) {
    this.parent = parent;
  }

  public void run() {
    Logger.log("Checking for new version started.");
    try {      
      DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
      Document document = documentBuilder.parse("http://www.ehsunbehravesh.com/mypasswords/pad_file.xml?ts=" + System.currentTimeMillis());
      document.getDocumentElement().normalize();
      Element elmProgramInfo = (Element) document.getDocumentElement().getElementsByTagName("Program_Info").item(0);
      Element elmProgramVersion = (Element) elmProgramInfo.getElementsByTagName("Program_Version").item(0);
      String strVersion = elmProgramVersion.getTextContent().trim();
      Domain domain = Domain.getInstance();
      float newVersion;
      try {
        newVersion = Float.parseFloat(strVersion);
      } catch (Exception ex) {
        newVersion = domain.getMyPasswordsVersion();
      }      
      if (newVersion > domain.getMyPasswordsVersion()) {
        //JOptionPane.showMessageDialog(this, "<html>MyPasswords version <b>" + newVersion + "</b> is available.</html>\nGet it on http://sourceforge.net/projects/mypasswords7.", "New Version", JOptionPane.INFORMATION_MESSAGE);
        int answer = JOptionPane.showConfirmDialog(parent, "<html>MyPasswords version <b>" + newVersion + "</b> is available.</html>\nGet it on http://sourceforge.net/projects/mypasswords7.", "New Version", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);
        if (answer == JOptionPane.YES_OPTION) {
          Utils.openURL("http://www.mypasswords7.com/download");
        }
      }      
    } catch (Exception ex) {
      Logger.log(ex.getMessage());
    }
    Logger.log("Checking for new version finished.");
  }
}
